﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using FluentValidation;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.NewsLetters.ModelValidators
{
	public class SMTPServerValidator : AbstractValidator<Models.SMTPSettings>
	{
		public SMTPServerValidator(Services.NewsLettersService newsLetterService)
		{
			RuleFor(m => m.Name).NotEmpty().WithMessage("Vous devez indiquer un nom");
			RuleFor(m => m.Port).GreaterThan(0).WithMessage("Le port du serveur doit etre supérieur à zero");
			RuleFor(m => m.Port).LessThan(65534).WithMessage("La valeur indiquée depasse la limite maximale");
			RuleFor(m => m.HostName).NotEmpty().WithMessage("Vous devez indiquer un serveur");
			Custom(settings =>
			{
				if (!settings.DKIMPrivateKey.IsNullOrEmpty()
					|| !settings.DKIMDomain.IsNullOrEmpty()
					|| !settings.DKIMSelector.IsNullOrEmpty())
				{
					if (settings.DKIMPrivateKey.IsNullOrEmpty())
					{
						return new FluentValidation.Results.ValidationFailure("DKIMPrivateKey", "La clé privée DKIM doit etre renseignée");
					}
					if (settings.DKIMSelector.IsNullOrEmpty())
					{
						return new FluentValidation.Results.ValidationFailure("DKIMPrivateKey", "La selecteur DKIM doit etre renseigné");
					}
					if (settings.DKIMDomain.IsNullOrEmpty())
					{
						return new FluentValidation.Results.ValidationFailure("DKIMPrivateKey", "La domaine DKIM doit etre renseigné");
					}
				}

				return null;
			});
			Custom(settings =>
				{
					var existing = newsLetterService.GetSMTPServerByName(settings.Name);
					if (existing != null
						&& existing.Id != settings.Id)
					{
						return new FluentValidation.Results.ValidationFailure("Name", "Ce nom de serveur est déjà utilisé");
					}
					return null;
				});

		}
	}
}
